package com.atguigu.scw.manager.service.impl;

import com.atguigu.project.MD5Util;
import com.atguigu.project.MyStringUtils;
import com.atguigu.scw.manager.bean.TUser;
import com.atguigu.scw.manager.bean.TUserExample;
import com.atguigu.scw.manager.constant.Constans;
import com.atguigu.scw.manager.dao.TUserMapper;
import com.atguigu.scw.manager.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    TUserMapper userMapper;

    @Override
    public boolean register(TUser user) {
        // 拿到用户信息，先加密密码
        // String saltString =  "$1$" + user.getLoginacct().substring(0, 6) + "HAHA";
        // String md5Crypt = Md5Crypt.md5Crypt(user.getUserpswd().getBytes(), saltString);
        // 使用自己写的加密类
        String md5Crypt = MD5Util.digest(user.getUserpswd());
        user.setUserpswd(md5Crypt);
        // 再将用户的其他信息设置默认值
        // 设置昵称，创建时间(String)
        user.setUsername(user.getLoginacct());
        user.setCreatetime(MyStringUtils.formatSimpleDate(new Date()));
        // 去数据库保存用户
        int i = 0;
        try {
            i = userMapper.insertSelective(user);
        } catch (Exception e) {
            logger.error("数据库写入异常", e);
            return false;
        }
        return i == 1;
    }

    @Override
    public TUser login(TUser user) {
        // 去数据库查询用户是否存在
        TUserExample example = new TUserExample();
        TUserExample.Criteria criteria = example.createCriteria();
        // 设置查询条件
        criteria.andLoginacctEqualTo(user.getLoginacct());
        criteria.andUserpswdEqualTo(MD5Util.digest(user.getUserpswd()));
        List<TUser> tUsers = null;
        try {
            tUsers = userMapper.selectByExample(example);
        } catch (Exception e) {
            logger.error("查询用户信息异常", e);
            return null;
        }
        return tUsers.size() == 1 ? tUsers.get(0) : null;
    }

    @Override
    public List<TUser> getAll() {
        return userMapper.selectByExample(null);
    }

    @Override
    public List<TUser> getAllByExample(TUserExample example) {
        return userMapper.selectByExample(example);
    }

    @Override
    public void deleteBatchOrSingle(String ids) {
        if (ids.contains(",")) {
            ArrayList<Integer> idList = new ArrayList<>();
            String[] split = ids.split(",");
            for (String s : split) {
                int id = 0;
                try {
                    id = Integer.parseInt(s);
                } catch (NumberFormatException e) {
                    logger.error("id非数字", e);
                }
                idList.add(id);
            }
            TUserExample example = new TUserExample();
            TUserExample.Criteria criteria = example.createCriteria();
            // 删除id所在集合
            criteria.andIdIn(idList);
            userMapper.deleteByExample(example);
        } else {
            userMapper.deleteByPrimaryKey(Integer.parseInt(ids));
        }
    }

    @Override
    public void savaUser(TUser user) {
        user.setCreatetime(MyStringUtils.formatSimpleDate(new Date()));
        user.setUserpswd(MD5Util.digest(Constans.DEFAULT_USER_PASSWORD));
        userMapper.insertSelective(user);
    }

    @Override
    public TUser getUserById(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public void updateUser(TUser user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public Boolean sendEmail(String email) {
        Boolean exist = checkEmailExist(email);
        if (exist) {
            // 发送邮件
            // 生成令牌
            // 数据库中保存令牌
            // 把带令牌的链接发给用户
            return true;
        }
        return false;
    }

    @Override
    public Boolean checkEmailExist(String email) {
        TUserExample exmaple = new TUserExample();
        TUserExample.Criteria criteria = exmaple.createCriteria();
        criteria.andEmailEqualTo(email);
        // 系统设计来保证邮箱的唯一性
        List<TUser> userList = userMapper.selectByExample(exmaple);
        if (userList != null && userList.size() == 1) {
            return true;
        }
        return false;
    }

    // 测试使用的代码：
    // @Override
    // public TUser getUserById(Integer id) {
    //     return userMapper.selectByPrimaryKey(id);
    // }
    //
    // @Override
    // public void saveUser(TUser user) {
    //     userMapper.insert(user);
    //     // throw new RuntimeException();
    // }
    //
}
